package org.dromara.data.dnnyun.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.components.sysRegion.constant.SysRegionConstants;
import org.dromara.components.sysRegion.domain.bo.SysRegionBo;
import org.dromara.components.sysRegion.service.ISysRegionService;
import org.dromara.curd.dnnyun.domain.bo.DnnyunConsumeOrderBo;
import org.dromara.curd.dnnyun.domain.bo.DnnyunStoreAchievementBo;
import org.dromara.curd.dnnyun.domain.bo.DnnyunStoreBo;
import org.dromara.curd.dnnyun.domain.vo.DnnyunStoreVo;
import org.dromara.curd.dnnyun.service.IDnnyunConsumeOrderService;
import org.dromara.curd.dnnyun.service.IDnnyunStoreAchievementService;
import org.dromara.curd.dnnyun.service.IDnnyunStoreService;
import org.dromara.data.dnnyun.service.IDnnyunDataService;
import org.dromara.third.dnnyun.constant.DyConstants;
import org.dromara.third.dnnyun.domain.DyConsumeOrder;
import org.dromara.third.dnnyun.domain.DyRegion;
import org.dromara.third.dnnyun.domain.DyStore;
import org.dromara.third.dnnyun.domain.DyStoreAchievement;
import org.dromara.third.dnnyun.domain.bo.DyConsumeOrderBo;
import org.dromara.third.dnnyun.domain.bo.DyStoreAchievementBo;
import org.dromara.third.dnnyun.domain.bo.DyStoreBo;
import org.dromara.third.dnnyun.domain.vo.*;
import org.dromara.third.dnnyun.service.IDnnyunService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author: wangdm
 * @date 2024/02/19 23:37
 * @Description:
 */
@Service
public class DnnyunDataServiceImpl implements IDnnyunDataService {
    @Resource
    private IDnnyunService dnnyunService;
    @Resource
    private ISysRegionService sysRegionService;
    @Resource
    private IDnnyunStoreService dnnyunStoreService;
    @Resource
    private IDnnyunConsumeOrderService dnnyunConsumeOrderService;
    @Resource
    private IDnnyunStoreAchievementService dnnyunStoreAchievementService;

    private int syncPerPageSize = 200;

    /**
     * 同步东云的省市区街道
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncProvince() {
        DyProvinceListResp dyProvinceListResp = dnnyunService.getProvinceList();
        if(DyConstants.RETURN_CODE_SUCCESS == dyProvinceListResp.getReturnCode()){
            //获取省份列表
            DyRegionListVo dyProvinceListVo = dyProvinceListResp.getData();
            List<DyRegion> provinceList = dyProvinceListVo.getRegion();
            if(CollectionUtil.isNotEmpty(provinceList)){
                //删除原数据库中的省份信息
                sysRegionService.deleteByType(SysRegionConstants.SYS_REGION_TYPE_PROVINCE);
                //批量入库当前省份信息
                List<SysRegionBo> batchInsertBoList = new ArrayList<>();
                for (DyRegion provinceObj:provinceList) {
                    SysRegionBo sysRegionBo = BeanUtil.copyProperties(provinceObj, SysRegionBo.class);
                    sysRegionBo.setType(SysRegionConstants.SYS_REGION_TYPE_PROVINCE);
                    batchInsertBoList.add(sysRegionBo);
                    //同步市信息
                    syncCity(sysRegionBo.getId());
                }
                sysRegionService.insertBatchByBo(batchInsertBoList);
            }
        }else{
            throw new ServiceException(dyProvinceListResp.getReturnMsg());
        }
    }

    @Override
    public void syncCity(Long provinceId) {
        DyCityListResp dyProvinceListResp = dnnyunService.getCityList(provinceId);
        if(DyConstants.RETURN_CODE_SUCCESS == dyProvinceListResp.getReturnCode()){
            //获取省市区街道列表
            DyRegionVo provinceObj = dyProvinceListResp.getData();
            DyRegion region = provinceObj.getRegion();
            List<DyRegion> cityList = region.getChildren();
            if(CollectionUtil.isNotEmpty(cityList)){
                //删除原数据库中的市信息
                sysRegionService.deleteByParentId(provinceId);
                //批量入库当前市信息
                List<SysRegionBo> batchInsertBoList = new ArrayList<>();
                for (DyRegion cityObj:cityList) {
                    SysRegionBo sysRegionBo = BeanUtil.copyProperties(cityObj, SysRegionBo.class);
                    sysRegionBo.setType(SysRegionConstants.SYS_REGION_TYPE_CITY);
                    sysRegionBo.setParentId(provinceId);
                    batchInsertBoList.add(sysRegionBo);
                    //同步区信息
                    syncCounty(sysRegionBo.getId(),cityObj.getChildren());
                }
                sysRegionService.insertBatchByBo(batchInsertBoList);
            }
        }else{
            throw new ServiceException(dyProvinceListResp.getReturnMsg());
        }
    }

    @Override
    public void syncCounty(Long cityId,List<DyRegion> countyList) {
        if(CollectionUtil.isNotEmpty(countyList)){
            //删除原数据库中的区信息
            sysRegionService.deleteByParentId(cityId);
            //批量入库当前区县信息
            List<SysRegionBo> batchInsertBoList = new ArrayList<>();
            for (DyRegion countyObj:countyList) {
                SysRegionBo sysRegionBo = BeanUtil.copyProperties(countyObj, SysRegionBo.class);
                sysRegionBo.setType(SysRegionConstants.SYS_REGION_TYPE_COUNTY);
                sysRegionBo.setParentId(cityId);
                batchInsertBoList.add(sysRegionBo);
                //同步街道信息
                syncStreet(sysRegionBo.getId(),countyObj.getChildren());
            }
            sysRegionService.insertBatchByBo(batchInsertBoList);
        }

    }

    @Override
    public void syncStreet(Long countyId,List<DyRegion> streetList) {
        if(CollectionUtil.isNotEmpty(streetList)){
            //删除原数据库中的区信息
            sysRegionService.deleteByParentId(countyId);
            //批量入库当前区县信息
            List<SysRegionBo> batchInsertBoList = new ArrayList<>();
            for (DyRegion countyObj:streetList) {
                SysRegionBo sysRegionBo = BeanUtil.copyProperties(countyObj, SysRegionBo.class);
                sysRegionBo.setType(SysRegionConstants.SYS_REGION_TYPE_STREET);
                sysRegionBo.setParentId(countyId);
                batchInsertBoList.add(sysRegionBo);
            }
            sysRegionService.insertBatchByBo(batchInsertBoList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncStore() {
        DyStoreBo dyStoreBo = new DyStoreBo();
        DyStoreListResp dyStoreListResp = dnnyunService.getDyStoreList(dyStoreBo);
        if(DyConstants.RETURN_CODE_SUCCESS == dyStoreListResp.getReturnCode()){
            List<DyStore> dyStoreList = dyStoreListResp.getData();
            if(CollectionUtil.isNotEmpty(dyStoreList)){
                List<DnnyunStoreBo> insertBoList = new ArrayList<>();
                for (DyStore dyStore:dyStoreList) {
                    DnnyunStoreBo bo = BeanUtil.copyProperties(dyStore, DnnyunStoreBo.class);
                    bo.setParentId(dyStore.getPId());
                    insertBoList.add(bo);
                }
                //删除门店数据
                dnnyunStoreService.deleteStore();
                //批量新增
                dnnyunStoreService.insertBatchByBo(insertBoList);
            }
            //刷新祖级
            dnnyunStoreService.refreshAncestors(null);
        }else{
            throw new ServiceException(dyStoreListResp.getReturnMsg());
        }
    }

    private void getDyConsumeOrderList(DyConsumeOrderBo dyConsumeOrderBo){
        String orderTimeBegin = dyConsumeOrderBo.getOrderTimeBegin();
        String orderTimeEnd = dyConsumeOrderBo.getOrderTimeEnd();
        if(StringUtils.isBlank(orderTimeBegin) || StringUtils.isBlank(orderTimeEnd) ){
            throw new ServiceException("时间范围不能为空");
        }
        Map<String,Object> params = new HashMap<>();
        params.put("beginOrderTime",orderTimeBegin);
        params.put("endOrderTime",orderTimeEnd);

        DyConsumerOrderListResp dyConsumerOrderListResp = dnnyunService.getDyConsumeOrderList(dyConsumeOrderBo);
        if(DyConstants.RETURN_CODE_SUCCESS == dyConsumerOrderListResp.getReturnCode()){
            DyConsumeOrderListVo dyConsumeOrderListVo = dyConsumerOrderListResp.getData();
            if(null != dyConsumeOrderListVo){
                //总条数
                Integer totalCount = dyConsumeOrderListVo.getCount();
                List<DyConsumeOrder> dyConsumeOrderList = dyConsumeOrderListVo.getData();
                if(CollectionUtil.isNotEmpty(dyConsumeOrderList)){
                    List<DnnyunConsumeOrderBo> insertBoList = new ArrayList<>();
                    for (DyConsumeOrder dyConsumeOrder:dyConsumeOrderList) {
                        DnnyunConsumeOrderBo bo = BeanUtil.copyProperties(dyConsumeOrder, DnnyunConsumeOrderBo.class);
                        bo.setStoreId(dyConsumeOrderBo.getStoreId());
                        insertBoList.add(bo);
                    }
                    //第1页同步时，先删除数据
                    if(dyConsumeOrderBo.getPage() == 1){
                        DnnyunConsumeOrderBo deleteBo = new DnnyunConsumeOrderBo();
                        deleteBo.setStoreId(dyConsumeOrderBo.getStoreId());
                        deleteBo.setParams(params);
                        dnnyunConsumeOrderService.deleteByStoreId(deleteBo);
                    }
                    //插入本次同步数据
                    dnnyunConsumeOrderService.insertBatchByBo(insertBoList);
                    //未到最后一页时，继续查询下一页
                    if(totalCount > dyConsumeOrderBo.getPage()*dyConsumeOrderBo.getLimit()){
                        dyConsumeOrderBo.setPage(dyConsumeOrderBo.getPage()+1);
                        getDyConsumeOrderList(dyConsumeOrderBo);
                    }
                }
            }
        }else{
            throw new ServiceException(dyConsumerOrderListResp.getReturnMsg());
        }
    }

    /**
     * 同步东云消费订单-默认同步近7天的数据
     */
    @Override
    public void syncConsumeOrder(DyConsumeOrderBo dyConsumeOrderBo) {
        //没有上送时间区间时，默认同步近7天的数据
        if(ObjectUtil.isNull(dyConsumeOrderBo.getOrderTimeBegin()) || ObjectUtil.isNull(dyConsumeOrderBo.getOrderTimeEnd()) ){
            Date now = DateUtil.date();
            Date beginTime = DateUtil.beginOfDay(DateUtil.offsetDay(now,-7));
            Date endTime = DateUtil.endOfDay(now);
            dyConsumeOrderBo.setOrderTimeBegin(DateUtil.formatDateTime(beginTime));
            dyConsumeOrderBo.setOrderTimeEnd(DateUtil.formatDateTime(endTime));
        }
        //查询门店列表
        DnnyunStoreBo storeBo = new DnnyunStoreBo();
        //如果上送了门店，只同步已上送的门店
        if(null != dyConsumeOrderBo.getStoreId()){
            storeBo.setId(dyConsumeOrderBo.getStoreId());
        }
        List<DnnyunStoreVo> storeVoList = dnnyunStoreService.queryList(storeBo);
        if(CollectionUtil.isNotEmpty(storeVoList)){
            for (DnnyunStoreVo storeVo:storeVoList) {
                //根据门店id同步消息订单
                Long storeId = storeVo.getId();
                //门店id为空时不同步
                if(null == storeId){
                    continue;
                }
                DyConsumeOrderBo queryBo = new DyConsumeOrderBo();
                queryBo.setStoreId(storeId);
                queryBo.setOrderTimeBegin(dyConsumeOrderBo.getOrderTimeBegin());
                queryBo.setOrderTimeEnd(dyConsumeOrderBo.getOrderTimeEnd());
                int pageNum = 1;
                queryBo.setPage(pageNum);
                queryBo.setLimit(syncPerPageSize);
                getDyConsumeOrderList(queryBo);
            }
        }

    }

    @Override
    public void syncStoreAchievementList(DnnyunStoreAchievementBo bo) {
        //如果未指写时间范围，只查当天
        String dateFormat = "yyyy-MM-dd HH:mm:ss";
        Date now = DateUtil.date();
        Date beginOrderDate = DateUtil.beginOfDay(now);
        Date endOrderDate = DateUtil.endOfDay(now);
        Map<String, Object> params = bo.getParams();
        if(null != params.get("beginOrderDate") && null != params.get("endOrderDate")){
            beginOrderDate = DateUtil.parse((String) params.get("beginOrderDate"),dateFormat);
            endOrderDate = DateUtil.parse((String) params.get("endOrderDate"),dateFormat);
        }
        while(true){
            //开始时间比结束时间大时跳出循环
            if(DateUtil.compare(beginOrderDate,endOrderDate) > 0){
                break;
            }
            DyStoreAchievementBo storeAchievementBo = new DyStoreAchievementBo();
            storeAchievementBo.setStoreId(3272L);
            storeAchievementBo.setBeginTime(DateUtil.format(DateUtil.beginOfDay(beginOrderDate),"yyyy-MM-dd HH:mm:ss"));
            storeAchievementBo.setEndTime(DateUtil.format(DateUtil.endOfDay(beginOrderDate),"yyyy-MM-dd HH:mm:ss"));
            DyStoreAchievementResp dyResp = dnnyunService.getDyStoreAchievementList(storeAchievementBo);
            if(DyConstants.RETURN_CODE_SUCCESS == dyResp.getReturnCode()){
                List<DyStoreAchievement> dyStoreAchievementVoList = dyResp.getData();
                if(CollectionUtil.isNotEmpty(dyStoreAchievementVoList)){
                    List<DnnyunStoreAchievementBo> boList = new ArrayList<>();
                    for (DyStoreAchievement dyStoreAchievement:dyStoreAchievementVoList) {
                        if(dyStoreAchievement.getStoreId() == 0L){
                            //storeId=0为合计数据,不需要入库
                            continue;
                        }
                        DnnyunStoreAchievementBo insertBo = BeanUtil.copyProperties(dyStoreAchievement, DnnyunStoreAchievementBo.class);
                        insertBo.setOrderDate(beginOrderDate);
                        boList.add(insertBo);
                    }
                    //删除除当天的数据
                    dnnyunStoreAchievementService.deleteByOrderDate(beginOrderDate);
                    //批量插入
                    dnnyunStoreAchievementService.insertBatchByBo(boList);
                }
            }else{
                throw new ServiceException(dyResp.getReturnMsg());
            }
            beginOrderDate = DateUtil.offsetDay(beginOrderDate,1);
        }


    }
}
